import { Menu,Button,Table,message,Modal,Input,Spin,Form,Popconfirm  } from 'antd';
import type { MenuProps } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { useState,useEffect } from "react"

import { post } from "@/api/index"

import "./index.less"
const ArticleManage: React.FC = () => {
  const sideBarItems = [
    {
      label:'待审核',
      key:'toApprove'
    },
    {
      label:'已审核',
      key:'approved'
    },
    {
      label:'已退回',
      key:'rejected'
    },
  ]
  const [current, setCurrent] = useState('toApprove');
  const [pageData,setPageData] = useState([] as DataType[])
  const [messageApi,contextHolder] = message.useMessage();
  const [isOpen,setIsOpen] = useState(false) 
  const [isOpenToReject,setIsOpenToReject] = useState(false) 
  const [isOpenToPass,setIsOpenToPass] = useState(false) 
  const [previewUrl,setProviewUrl] = useState('')
  const [filterObj,setFilterObj] = useState({} as FilterObjType)
  const [filterTimer,setFiterTimer] = useState(0)
  const [isSpin,setIsSpin] = useState(false)
  const [curArtId,setCurArtId] = useState(0)
  const [form] = Form.useForm();
  interface DataType {
    status: string;
    title: string;
    name: string;
    createAt:string;
    image:string;
    action:string;
    text:string,
    artId:number;
    id:number,
    isOpenPopConfirm:boolean
  }
  interface FilterObjType {
    'title':string,
    'name':string
  }
  type titleType = 'title' | 'name'
  const titleLabelObj = {
    title:'文章标题',
    name:'作者'
  }
  // 按钮渲染器
  function BtnByCurrent(row:DataType){
    const { status,artId,isOpenPopConfirm } = row
    switch(status){
      case 'toApprove':
        return (
          <div>
            <Button onClick={()=>toViewDetail(artId)} type='link'>查看详情</Button>
            <Button onClick={()=>openModal(artId,'pass')} type='link'>审核通过</Button>
            <Button onClick={()=>openModal(artId,'return')} type='link'>退回</Button>
          </div>
        )
      case 'approved':
        return (
          <div>
            <Button onClick={()=>toViewDetail(artId)} type='link'>查看详情</Button>
            <Popconfirm
              title='撤销审核'
              description='您确定撤销该文章？'
              open={isOpenPopConfirm}
              cancelText='取消'
              okText='确认'
              onConfirm={()=>toResetReview(artId)}
              onCancel={()=>handlePopConfirmHide(artId)}
            >
              <Button onClick={()=>openPopConfirm(artId)} type='link'>撤销审核</Button>
            </Popconfirm>
          </div>
        )
      case 'rejected':
        return (
          <div>
            <Button onClick={()=>toViewDetail(artId)} type='link'>查看详情</Button>
            <Popconfirm
              title='撤销退回'
              description='您确定撤销退回该文章？'
              open={isOpenPopConfirm}
              cancelText='取消'
              okText='确认'
              onConfirm={()=>toResetReview(artId)}
              onCancel={()=>handlePopConfirmHide(artId)}
            >
              <Button onClick={()=>openPopConfirm(artId)} type='link'>撤销退回</Button>
            </Popconfirm>
          </div>
        )
    }
  }
  // 过滤表头渲染器
  function fliterHeader(title:string){
    return (
      <div className='filter'>
        <span>{titleLabelObj[title as titleType]}</span>
        <Input allowClear={true} placeholder={'请输入' + titleLabelObj[title as titleType]} onChange={(e)=>filterTable(e.target.value,title as titleType)}></Input>
      </div>
    )
  }
  const columns: ColumnsType<DataType> = [
    {
      title: fliterHeader('title'),
      dataIndex: 'title',
      ellipsis: {
        showTitle:true
      },
      width:'20%'
    },
    {
      title: fliterHeader('name'),
      dataIndex: 'name',
      width:'10%'
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      width:'10%'
    },
    {
      title: '配图',
      key: 'image',
      render:(row:DataType)=>{
        return <img onClick={()=>preViewImage(row.image)} className='art-img' src={process.env.REACT_APP_BASE_URL + row.image} alt="" />
      },
      width:'10%'
    },
    {
      title: '操作',
      key: 'action',
      render:(row:DataType)=>{
        return BtnByCurrent(row)
      },
      width:'20%'
    },
  ];
  
  // 变量
  const imgPreviewModalStyles = {
    body:{
      minWidth:500,
      display:'flex'
    }
  }
  // 事件
  // 关闭气泡框
  const handlePopConfirmHide = (id:number)=>{
    setPageData(pageData.map(item=>{
      if(item.artId === id){
        item.isOpenPopConfirm = false
      }
      return item
    }))
  }
  // 过滤table表格
  const filterTable = async (value:string,title:titleType)=>{
    setFilterObj({
      ...filterObj,
      [title]:value
    })
  }
  // 预览文章配图
  const preViewImage = (url:string)=>{
    setProviewUrl(process.env.REACT_APP_BASE_URL + url)
    setIsOpen(true)
  }
  // 打开popConfirm
  const openPopConfirm = (artId:number)=>{
    setPageData(pageData.map(item=>{
      if(item.isOpenPopConfirm) item.isOpenPopConfirm = false
      if(item.artId === artId){
        item.isOpenPopConfirm = true
      }
      return item
    }))
  }
  //撤销审核节点，恢复为待审核
  const toResetReview = async (artId:number)=>{
    const { code,message } = await post("/manage/toResetReview",{artId})
    if(code === 200){
      messageApi.success(message)
      await getArticleListByKey(current)
      return
    }else{
      messageApi.error(message)
    }
  }
  //拒绝文章接口
  const toReject = async ()=>{
    await form.validateFields().then(async (res)=>{
      const {...items} = res
      const { code,message } = await post("/manage/toRejectArticle",{artId:curArtId,...items})
      if(code === 200){
        messageApi.success(message)
        await getArticleListByKey(current)
        setIsOpenToReject(false)
        form.resetFields()
        return
      }else{
        messageApi.error(message)
      }
    }).catch(e=>{
      console.log(e.values)
    })
    
  }
  const openModal = async (artId:number,type:'pass' | 'return')=>{
    setCurArtId(artId)
    switch(type){
      case 'return':
        setIsOpenToReject(true)
        break;
      case 'pass':
        setIsOpenToPass(true)
        break;
    }
  }
  //审核文章接口
  const toApprove = async (artId:number)=>{
    try {
      const { code,message } = await post("/manage/toApproveArticle",{artId})
      if(code === 200){
        messageApi.success(message)
        await getArticleListByKey(current)
        return
      }else{
        messageApi.error(message)
      }
    }catch(e){
      console.log(e)
    }finally {
      setIsOpenToPass(false)
    }
    
  }
  // 获取文章分类列表
  const getArticleListByKey = async (status:string)=>{
    // 先判断过滤项是否为空
    let empty = true
    Object.keys(filterObj).forEach(item=>{
      if(filterObj[item as titleType]){
        empty = false
      }
    })
    const tempFilterObj = empty ? {} : filterObj
    try{
      setIsSpin(true)
      const { data } = empty ? await post("/manage/getTableData",{status}) : await post("/manage/getTableDataByFilter",{status,filterObj:tempFilterObj})
      setPageData(data.data.map((item:any)=>{
        return {
          ...item,
          isOpenPopConfirm:false
        }
      }))
    }catch(e){
      console.log(e)
    }finally{
      setTimeout(() => {
        setIsSpin(false)
      }, 500);
    }
  }
  const toViewDetail = async (artId:number)=>{
    // 获取token先，由于登录信息一致
    const token = sessionStorage.getItem("token")
    window.open(process.env.REACT_APP_FRONTEND_URL + `loginByManage/${artId}/${token}`)
  }
  // 切换导航栏
  const onClick: MenuProps['onClick'] = async (e)=>{
    if(e.key === current) return
    setCurrent(e.key)
  }
  useEffect(()=>{
    getArticleListByKey(current)
  },[current])
  useEffect(()=>{
    if(filterTimer){
      clearTimeout(filterTimer)
    }
    const timer:number = window.setTimeout(()=>{
      getArticleListByKey(current)
    },700) 
    setFiterTimer(timer)
  },[filterObj])
  return (
    <>
      {contextHolder}
      <div className="article-contain">
        <Menu
          onClick={onClick}
          style={{ width: '256px',height:'40px'}}
          selectedKeys={[current]}
          mode="horizontal"
          theme="light"
          items={sideBarItems}
          getPopupContainer={function test(node) {
            return node.parentNode as HTMLElement;
          }}
        />
        <Spin tip={'加载中'} spinning={isSpin}>
          <div className='right'>
              <Table rowKey={(row:any)=>row.artId} columns={columns} dataSource={pageData} pagination={false} scroll={{y:'calc(100vh - 192px)',x:'calc(100vw - 256px)'}}/>
          </div>
        </Spin>
        <Modal styles={imgPreviewModalStyles} open={isOpen} width={700} maskClosable={true} closable={false} footer={null} onCancel={()=>setIsOpen(false)}>
          <img style={{width:'97%',height:'500px',margin:'0 auto'}} src={previewUrl} alt="" />
        </Modal>
        <Modal cancelText="取消" okText="确认" title="确认退回?" open={isOpenToReject} width={600} maskClosable={false} closable={false} 
          onCancel={
            ()=>{
              form.resetFields() 
              setIsOpenToReject(false)
            }
          } 
          onOk={
            ()=>toReject()
          }>
          <Form form={form} style={{ maxWidth: 600 }}>
            <Form.Item
              label="退回原因"
              name="returnComment"
              rules={[{ required: true, message: '请输入退回原因' }]}
            >
              <Input placeholder="请输入退回原因" />
            </Form.Item>
          </Form>
        </Modal>
        <Modal cancelText="取消" okText="确认" title="确认审核通过?" open={isOpenToPass} width={600} maskClosable={false} closable={false} 
          onCancel={
            ()=>{
              setIsOpenToPass(false)
            }
          } 
          onOk={
            ()=>toApprove(curArtId)
          }>
            <p>您确认要审核通过该文章？</p>
        </Modal>
      </div>
    </>
  );
};

export default ArticleManage;